Shiny.addCustomMessageHandler("treemap2_values", function (message) {
    console.log(message);
    var data = message[0];
    var data1 = message[1];
    var nextScope = "regiao";
    //Parallel Coordinates code
    var traits = ["name", 'value', "Hora", "Dia", "Idade", "Sexo", "Causador"];
    // ,"CNAE"
    var parcoordstable = d3.select("#parallelcoordinates_table table");


    function reloadParallelCords(arrayData) {
        console.log(arrayData);
        dragging = {};
        var background;
        var m = [50, 50, 20, 100],
            w = window.innerWidth * 0.7 - m[1] - m[3],
            h = window.innerHeight * 0.5 - m[0] - m[2];
        var line = d3.line(),
            axis = d3.axisLeft(),
            foreground;
        var parcoords = d3.select("#parallelcoordinates_area").append("svg")
            .attr("width", w + m[1] + m[3])
            .attr("height", h + m[0] + m[2])
            .append("g")
            .attr("transform", "translate(" + m[3] + "," + m[0] + ")");
        // Create a scale and brush for each trait
        var x = d3.scalePoint().domain(traits).range([0, w]),
            y = {};

        traits.forEach(function (col) {
            if (col == "Dia") {
                var data = ["seg", "ter", "qua", "qui", "sex", "sáb", "dom"];
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else if (col == "name") {
                var data = [];
                arrayData.forEach(function (row) {
                    data.push(row[col]);
                })
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else if (col == "Causador" || col == "CNAE") {
                var data = [];
                arrayData.forEach(function (row) {
                    if (!arrayData.includes(row[col])) {
                        data.push(row[col]);
                    }
                })
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else {
                arrayData.forEach(function (p) {
                    p[col] = +p[col];
                });
                if (col == "Sexo") {
                    y[col] = d3.scaleLinear()
                        .domain(
                            [0, 1]
                        )
                        .range([h, 0]);
                } else {
                    y[col] = d3.scaleLinear()
                        .domain(d3.extent(arrayData, function (p) {
                            return p[col];
                        }))
                        .range([h, 0]);
                }
            }
            //Create Brush
            y[col].brush = d3.brushY()
                .extent([
                    [-7, y[col].range()[1]],
                    [7, y[col].range()[0]]
                ])
                .on("start", brushstart)
                .on("brush", brushView)
                .on("end", brush);
        });

        //Append Background
        background = parcoords.append("g")
            .attr("class", "background")
            .selectAll("path")
            .data(arrayData)
            .enter().append("path")
            .attr("d", path);

        //Add Foreground Lines
        foreground = parcoords.append("g")
            .attr("class", "foreground")
            .selectAll("path")
            .data(arrayData)
            .enter().append("path")
            .attr("d", path)
            .attr("class", function (d) {
                return d.name;
            });

        // Add a group element for each trait.
        var g = parcoords.selectAll(".trait")
            .data(traits)
            .enter()
            .append("svg:g")
            .attr("class", "trait")
            .attr("transform", function (d) {
                return "translate(" + x(d) + ")";
            })
            .call(d3.drag()
                .subject(function (d) {
                    return {
                        x: x(d)
                    };
                })
                .on("start", function (d) {
                    dragging[d] = x(d);
                    background.attr("visibility", "hidden");
                })
                .on("drag", function (d) {
                    //+10 e -10 para mudar com o primeiro e o ultimo
                    dragging[d] = Math.min(w + 10, Math.max(-10, d3.event.x));
                    foreground.attr("d", path);
                    traits.sort(function (a, b) {
                        return position(a) - position(b);
                    });
                    x.domain(traits);
                    g.attr("transform", function (d) {
                        return "translate(" + position(d) + ")";
                    })
                })
                .on("end", function (d) {
                    delete dragging[d];
                    transition(d3.select(this)).attr("transform", "translate(" + x(d) + ")");
                    transition(foreground).attr("d", path);
                    background
                        .attr("d", path)
                        .transition()
                        .delay(500)
                        .duration(0)
                        .attr("visibility", null);
                })
            );

        //Gradiente do eixo Sexo
        var defs = parcoords.append("defs");
        var gradient = defs.append("linearGradient")
            .attr("id", "svgGradient")
            .attr("x1", "50%")
            .attr("x2", "100%")
            .attr("y1", "50%")
            .attr("y2", "100%");
        gradient.append("stop")
            .attr('class', 'start')
            .attr("offset", "0%")
            .attr("stop-color", "blue")
            .attr("stop-opacity", 1);
        gradient.append("stop")
            .attr('class', 'end')
            .attr("offset", "100%")
            .attr("stop-color", "red")
            .attr("stop-opacity", 1);
        //Eixos  
        g.append("svg:g")
            .attr("class", "axis")
            .each(function (col) {
                if (col == "Sexo") {
                    d3.select(this)
                        .attr("class", "eixoSexo")
                        .call(d3.axisLeft(y[col]))
                        .selectAll("text").remove();
                    d3.select(this)
                        .call(d3.axisLeft(y[col])
                            .ticks(3));
                    d3.select(this)
                        .append("svg:text").text("M")
                        .attr("x", -9)
                        .attr("y", 10);
                    d3.select(this)
                        .append("svg:text").text("F")
                        .attr("x", -9)
                        .attr("y", h + 2);
                } else if (col == "Hora") {
                    d3.select(this).call(d3.axisLeft(y[col]).ticks(18));
                } else if (col == "Causador") {
                    // ALT
                    d3.select(this).call(d3.axisLeft(y[col])).selectAll("text")._groups[0].forEach(function (p) {
                        p.innerHTML = p.innerHTML.split(" ")[0];
                    })
                } else if (col == "Dia") {
                    // ALT
                    d3.select(this).call(d3.axisLeft(y[col])).selectAll("text")._groups[0].forEach(function (p) {
                        p.innerHTML = p.innerHTML.split(" ")[0];
                    })
                } else {
                    d3.select(this).call(d3.axisLeft(y[col]));
                }
            })
            // Axis titles
            .append("svg:text")
            .attr("text-anchor", "middle")
            .attr("y", -15)
            .text(function (col) {
                if (col != "value" && col != "name") {
                    return col;
                } else if (col == "value") {
                    return "Acidentes"
                } else if (col == "name") {
                    return "Escopo"
                }

            });

        // Add a brush for each axis.
        g.append("svg:g")
            .attr("class", "brush")
            .each(function (d) {
                d3.select(this).call(y[d].brush);
            })
            .selectAll("rect")
            .attr("x", -8)
            .attr("width", 16);

        function position(d) {
            var v = dragging[d];
            return v == null ? x(d) : v;
        }

        function transition(g) {
            return g.transition().duration(500);
        }
        // Returns the path for a given data point.
        function path(d) {
            return line(traits.map(function (p) {
                return [position(p), y[p](d[p])];
            }));
        }

        // Brush functions
        function brushstart() {
            d3.event.sourceEvent.stopPropagation();
        }

        function brushView() {
            var actives = [];
            //filter brushed extents
            parcoords.selectAll(".brush")
                .filter(function (d) {
                    return d3.brushSelection(this);
                })
                .each(function (d) {

                    actives.push({
                        dimension: d,
                        extent: d3.brushSelection(this)
                    });
                    dim = actives[0].dimension;
                });
            //set un-brushed foreground line disappear
            foreground.classed("fade", function (d, i) {
                return !actives.every(function (active) {
                    var dim = active.dimension;
                    return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[
                        1];
                });
            });
        }

        function brush() {
            var actives = [];
            //filter brushed extents
            parcoords.selectAll(".brush")
                .filter(function (d) {
                    return d3.brushSelection(this);
                })
                .each(function (d) {
                    actives.push({
                        dimension: d,
                        extent: d3.brushSelection(this)
                    });

                    var selected = arrayData.filter(function (d) {
                        return actives.every(function (active) {
                            var dim = active.dimension;
                            return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
                        });
                    });

                    hideTableColNames();
                    d3.selectAll(".row_data").remove();

                    showTableColNames();

                    selected.forEach(function (d) {
                        var row = parcoordstable.append("tr")
                            .attr("class", "row_data")
                        traits.forEach(
                            function (string) {
                                row.append("td")
                                    .text(d[string]);
                            }
                        )
                    })

                });
            foreground.classed("fade", function (d, i) {
                return !actives.every(function (active) {
                    var dim = active.dimension;
                    return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
                });
            });
        }

        function hideTableColNames() {
            parcoordstable.style("visibility", "hidden");
        }

        function showTableColNames() {
            parcoordstable.style("visibility", "visible");
        }
    }

    function toggleAxis(checkBox, trait, data) {
        if (checkBox.checked == true) {
            if (!traits.includes(trait))
                traits.push(trait);
        }
        if (checkBox.checked == false) {
            var i = traits.indexOf(trait);
            traits.splice(i, 1);
        }
        d3.select("#parallelcoordinates_area svg").remove();
        reloadParallelCords(data);
    }

    var checkboxes = d3.select("#parallelcoordinates_area")
        .append("div")
        .attr("id", "parallelcoordinates_switch");

    function reloadCheckBoxes(data) {
        traits.forEach(function (trait) {
            checkboxes.append("input")
                .attr("type", "checkbox")
                .attr("id", trait)
                .attr("value", trait)
                .attr("checked", true)
                .on("click", function () {
                    toggleAxis(this, trait, data);
                });
            checkboxes.append("text")
                .text(trait);
        });
    }

    reloadCheckBoxes(data.children);
    reloadParallelCords(data.children);

    // ===========================================================================
    // Parallel Coords Cities Code
    // ============================================================================


    function reloadParallelCordsCities(arrayData) {
        dragging = {};
        var background;
        var m = [40, 50, 20, 150],
            w = window.innerWidth * 0.7 - m[1] - m[3],
            h = window.innerHeight * 0.5 - m[0] - m[2];
        var line = d3.line(),
            axis = d3.axisLeft(),
            foreground;
        var parcoords = d3.select("#parallelcoordinates_area_cities").append("svg")
            .attr("width", w + m[1] + m[3])
            .attr("height", h + m[0] + m[2])
            .append("g")
            .attr("transform", "translate(" + m[3] + "," + m[0] + ")");
        // Create a scale and brush for each trait
        var x = d3.scalePoint().domain(traits).range([0, w]),
            y = {};

        traits.forEach(function (col) {
            if (col == "Dia") {
                var data = ["seg", "ter", "qua", "qui", "sex", "sáb", "dom"];
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else if (col == "name") {
                var data = [];
                arrayData.forEach(function (row) {
                    data.push(row[col]);
                })
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else if (col == "Causador" || col == "CNAE") {
                var data = [];
                arrayData.forEach(function (row) {
                    if (!arrayData.includes(row[col])) {
                        data.push(row[col]);
                    }
                })
                y[col] = d3.scalePoint()
                    .domain(data)
                    .range([h, 0]);
            } else {
                arrayData.forEach(function (p) {
                    p[col] = +p[col];
                });
                if (col == "Sexo") {
                    y[col] = d3.scaleLinear()
                        .domain(
                            [0, 1]
                        )
                        .range([h, 0]);
                } else {
                    y[col] = d3.scaleLinear()
                        .domain(d3.extent(arrayData, function (p) {
                            return p[col];
                        }))
                        .range([h, 0]);
                }
            }
            //Create Brush
            y[col].brush = d3.brushY()
                .extent([
                    [-7, y[col].range()[1]],
                    [7, y[col].range()[0]]
                ])
                .on("start", brushstart)
                .on("brush", brushView)
                .on("end", brush);
        });

        //Append Background
        background = parcoords.append("g")
            .attr("class", "background")
            .selectAll("path")
            .data(arrayData)
            .enter().append("path")
            .attr("d", path);

        //Add Foreground Lines
        foreground = parcoords.append("g")
            .attr("class", "foreground")
            .selectAll("path")
            .data(arrayData)
            .enter().append("path")
            .attr("d", path)
            .style("stroke", function (d) {
                return colorMake(toColor.indexOf(d[nextScope]));
            });


        // Add a group element for each trait.
        var g = parcoords.selectAll(".trait")
            .data(traits)
            .enter()
            .append("svg:g")
            .attr("class", "trait")
            .attr("transform", function (d) {
                return "translate(" + x(d) + ")";
            })
            .call(d3.drag()
                .subject(function (d) {
                    return {
                        x: x(d)
                    };
                })
                .on("start", function (d) {
                    dragging[d] = x(d);
                    background.attr("visibility", "hidden");
                })
                .on("drag", function (d) {
                    //+10 e -10 para mudar com o primeiro e o ultimo
                    dragging[d] = Math.min(w + 10, Math.max(-10, d3.event.x));
                    foreground.attr("d", path);
                    traits.sort(function (a, b) {
                        return position(a) - position(b);
                    });
                    x.domain(traits);
                    g.attr("transform", function (d) {
                        return "translate(" + position(d) + ")";
                    })
                })
                .on("end", function (d) {
                    delete dragging[d];
                    transition(d3.select(this)).attr("transform", "translate(" + x(d) + ")");
                    transition(foreground).attr("d", path);
                    background
                        .attr("d", path)
                        .transition()
                        .delay(500)
                        .duration(0)
                        .attr("visibility", null);
                })
            );

        //Gradiente do eixo Sexo
        var defs = parcoords.append("defs");
        var gradient = defs.append("linearGradient")
            .attr("id", "svgGradient")
            .attr("x1", "50%")
            .attr("x2", "100%")
            .attr("y1", "50%")
            .attr("y2", "100%");
        gradient.append("stop")
            .attr('class', 'start')
            .attr("offset", "0%")
            .attr("stop-color", "blue")
            .attr("stop-opacity", 1);
        gradient.append("stop")
            .attr('class', 'end')
            .attr("offset", "100%")
            .attr("stop-color", "red")
            .attr("stop-opacity", 1);
        //Axis
        g.append("svg:g")
            .attr("class", "axis")
            .each(function (col) {
                if (col == "Sexo") {
                    d3.select(this)
                        .attr("class", "eixoSexo")
                        .call(d3.axisLeft(y[col]))
                        .selectAll("text").remove();
                    d3.select(this)
                        .call(d3.axisLeft(y[col])
                            .ticks(3));
                    d3.select(this)
                        .append("svg:text").text("M")
                        .attr("x", -9)
                        .attr("y", 10);
                    d3.select(this)
                        .append("svg:text").text("F")
                        .attr("x", -9)
                        .attr("y", h + 2);
                } else if (col == "Hora") {
                    d3.select(this).call(d3.axisLeft(y[col]).ticks(18));
                } else if (col == "Causador") {
                    // ALT
                    d3.select(this).call(d3.axisLeft(y[col])).selectAll("text")._groups[0].forEach(function (p) {
                        p.innerHTML = p.innerHTML.split(" ")[0];
                    })
                } else if (col == "Dia") {
                    // ALT
                    d3.select(this).call(d3.axisLeft(y[col])).selectAll("text")._groups[0].forEach(function (p) {
                        p.innerHTML = p.innerHTML.split(" ")[0];
                    })
                } else {
                    d3.select(this).call(d3.axisLeft(y[col]));
                }
            })
            // Axis Titles
            .append("svg:text")
            .attr("text-anchor", "middle")
            .attr("y", -15)
            .text(function (col) {
                if (col != "value" && col != "name") {
                    return col;
                } else if (col == "value") {
                    return "Acidentes"
                } else if (col == "name") {
                    return "Escopo Cities"
                }
            });

        // Add a brush for each axis.
        g.append("svg:g")
            .attr("class", "brush")
            .each(function (d) {
                d3.select(this).call(y[d].brush);
            })
            .selectAll("rect")
            .attr("x", -8)
            .attr("width", 16);

        function position(d) {
            var v = dragging[d];
            return v == null ? x(d) : v;
        }

        function transition(g) {
            return g.transition().duration(500);
        }
        // Returns the path for a given data point.
        function path(d) {
            return line(traits.map(function (p) {
                return [position(p), y[p](d[p])];
            }));
        }

        // BRUSH FUNCTIONS
        function brushstart() {
            d3.event.sourceEvent.stopPropagation();
        }

        function brushView() {
            var actives = [];
            //filter brushed extents
            parcoords.selectAll(".brush")
                .filter(function (d) {
                    return d3.brushSelection(this);
                })
                .each(function (d) {

                    actives.push({
                        dimension: d,
                        extent: d3.brushSelection(this)
                    });
                    dim = actives[0].dimension;
                });
            //set un-brushed foreground line disappear
            foreground.classed("fade", function (d, i) {
                return !actives.every(function (active) {
                    var dim = active.dimension;
                    return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[
                        1];
                });
            });
        }

        function brush() {
            var actives = [];
            //filter brushed extents
            parcoords.selectAll(".brush")
                .filter(function (d) {
                    return d3.brushSelection(this);
                })
                .each(function (d) {
                    actives.push({
                        dimension: d,
                        extent: d3.brushSelection(this)
                    });

                    var selected = arrayData.filter(function (d) {
                        return actives.every(function (active) {
                            var dim = active.dimension;
                            return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
                        });
                    });

                    hideTableColNames();
                    d3.selectAll(".row_data").remove();
                    showTableColNames();

                    selected.forEach(function (d) {
                        var row = parcoordstable.append("tr")
                            .attr("class", "row_data")
                        traits.forEach(
                            function (string) {
                                row.append("td")
                                    .text(d[string]);
                            }
                        )
                    })

                });



            foreground.classed("fade", function (d, i) {
                return !actives.every(function (active) {
                    var dim = active.dimension;
                    return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
                });
            });
        }


        function hideTableColNames() {
            parcoordstable.style("visibility", "hidden");
        }

        function showTableColNames() {
            parcoordstable.style("visibility", "visible");
        }
    }


    function toggleAxisCities(checkBox, trait, data) {
        if (checkBox.checked == true) {
            if (!traits.includes(trait))
                traits.push(trait);
        }
        if (checkBox.checked == false) {
            var i = traits.indexOf(trait);
            traits.splice(i, 1);
        }
        d3.select("#parallelcoordinates_area_cities svg").remove();
        reloadParallelCordsCities(data);
    }

    var checkboxescities = d3.select("#parallelcoordinates_area_cities")
        .append("div")
        .attr("id", "parallelcoordinates_switch_cities");

    function reloadCheckBoxesCities(data) {
        traits.forEach(function (trait) {
            checkboxescities.append("input")
                .attr("type", "checkbox")
                .attr("id", trait)
                .attr("value", trait)
                .attr("checked", true)
                .on("click", function () {
                    toggleAxisCities(this, trait, data);
                });
            checkboxescities.append("text")
                .text(trait);
        });
    }

    // TRANSPOSE OF DATA THAT COME FROM R READ OF CSV
    var values = ["municipio", "acidentes_municipio", "hora_municipio", "diaSemana_municipio", "idadeMedia_municipio", "sexoPorcentagem_municipio", "dsAgenteModa_municipio", "classeCnaeModa_municipio"];
    var values2 = ["regiao", "uf", "mesorregiao", "microrregiao"];

    function transposeData(d) {
        var len = d.pais.length;
        var datainsert = [];
        var dataTransposed = [];
        var i, j;

        for (i = 0; i < len; i++) {
            for (j = 0; j < values.length; j++) {
                datainsert[traits[j]] = d[values[j]][i];
            };

            values2.forEach(function (value2) {
                datainsert[value2] = d[value2][i];
            })



            dataTransposed.push(datainsert);
            datainsert = [];
        }
        return dataTransposed;
    }



    var colorMake = color = d3.scaleOrdinal().range(d3.schemeCategory10);

    var toColorDup = data1[nextScope];
    toColor = toColorDup.filter(function (elem, index, self) {
        return index === self.indexOf(elem);
    });

    var i0;
    var colors_subtitle = [];
    for (i0 = 0; i0 < toColor.length; i0++) {
        colors_subtitle.push({
            name: toColor[i0],
            color: colorMake(i0)
        });
    }

    dataTranspose = transposeData(data1);

    reloadCheckBoxesCities(dataTranspose);
    reloadParallelCordsCities(dataTranspose);

    var s1 = d3.select("#parallel_coordinates_subtitle").selectAll('div').data(colors_subtitle).enter().append("div").append("text");

    s1Attr = s1.text(function (d) {
            return d.name;
        })
        .style("color", function (d) {
            return d.color;
        })
        .style("font-weight", "bold");

    //Treemap code
    var margin = {
            top: 25,
            right: 0,
            bottom: 0,
            left: 0
        },
        width = window.innerWidth * 0.55,
        height = window.innerHeight * 0.5,
        formatNumber = d3.format(",d"),
        transitioning,
        hovering;


    var tooltip = d3.select("body")
        .append("div")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("visibility", "hidden")
        .style("color", "white")
        .style("padding", "8px")
        .style("background-color", "rgba(0, 0, 0, 0.75)")
        .style("border-radius", "6px")
        .style("font", "12px sans-serif")
        .text("tooltip");


    var x = d3.scaleLinear()
        .domain([0, width])
        .range([0, width]);

    var y = d3.scaleLinear()
        .domain([0, height - margin.top - margin.bottom])
        .range([0, height - 3 * margin.top - margin.bottom]);

    var c = [];

    function q(d) {
        for (var i = 0; i < d.children.length; i++) {
            c[i] = d.children[i].value;
            //Do something
        }

        return c.sort(function (a, b) {
            return (a - b);
        });
    }
    q(data);

    var maxValue = c[c.length - 1];
    var minValue = maxValue / 9;

    var color = d3.scaleThreshold()
        .domain([minValue, minValue * 2, minValue * 3, minValue * 4, minValue * 5, minValue * 6, minValue * 7, minValue * 8])
        .range(d3.schemeBlues[9]);

    var format = d3.format(",d");
    var createTreemap;
    var treemap, grandparent;

    updateDrillDown();

    function updateDrillDown() {
        if (treemap) {
            treemap.selectAll("*").remove();
        } else {
            //		 var treemap = d3.layout.treemap()
            //	      .children(function(d, depth) { return depth ? null : d._children; })
            //	      .sort(function(a, b) { return a.value - b.value; })
            //	      .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
            //	      .round(false);

            treemap = d3.select("#treemap2_area").append("svg")
                .attr("width", width - margin.left - margin.right)
                .attr("height", height - margin.bottom - margin.top)
                .style("margin-left", -margin.left + "px")
                .style("margin.right", -margin.right + "px")
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                .style("shape-rendering", "crispEdges");

            grandparent = treemap.append("g")
                .attr("class", "grandparent");

            grandparent.append("rect")
                .style("fill", "#ADEAEA")
                .style("padding", "1px")
                .attr("y", -margin.top)
                .attr("width", width)
                .attr("height", margin.top);

            grandparent.append("text")
                .attr("x", 6)
                .attr("y", 6 - margin.top)
                .attr("dy", ".75em");

            createTreemap = d3.treemap()
                .tile(d3.treemapBinary) //.ratio(height / width * 0.5 * (1 + Math.sqrt(5))/2))
                .size([width, height - 10])
                .round(false)
                .paddingInner(0);
        }

        var root = d3.hierarchy(data)
            .eachBefore(function (d) {
                d.id = (d.parent ? d.parent.id + "." : "") + d.data.name;
            })
            //.sum((d) => d.value)
            .sum(function (d) {
                //console.log(d.value);
                return d.value;
            })
            .sort(function (a, b) {
                //console.log('initial root sort a ' + a.value + ' b ' + b.value);
                return b.height - a.height || b.value - a.value;
            });

        initialize(root);
        accumulate(root);
        layout(root);
        createTreemap(root);
        display(root);

    };

    function initialize(root) {
        root.x = root.y = 0;
        root.x1 = width;
        root.y1 = height;
        root.depth = 0;

    }

    function accumulate(d) {
        return (d._children = d.children) ?
            d.value = d.children.reduce(function (p, v) {
                return p + accumulate(v);
            }, 0) : d.value;
    }

    function layout(d) {
        if (d._children) {
            //    treemap.nodes({_children: d._children});
            //	  treemap(d);
            d._children.forEach(function (c) {
                /*c.x0 = d.x0 + c.x0 * (d.x1 - d.x0);
				c.y0 = d.y0 + c.y0 * (d.y1 - d.y0);
				c.x1 *= d.x1;
				c.y1 *= d.y1;*/
                c.x0 = d.x0 + c.x0 * d.x1;
                c.y0 = d.y0 + c.y0 * d.y1;
                c.x1 *= (d.x1 - d.x0);
                c.y1 *= (d.y1 - d.y0);
                c.parent = d;
                layout(c);
            });
        }
    }

    function display(d) {
        grandparent
            .datum(d.parent)
            .on("click", transition)
            .select("text")
            .text(name(d));


        var g1 = treemap.insert("g", ".grandparent")
            .datum(d)
            .attr("class", "depth");

        var g = g1.selectAll("g")
            .data(d._children)
            .enter().append("g").style("opacity", 1);

        //aqui
        g.filter(function (d) {
                return d._children;
            })
            .classed("children", true)
            .on("click", transition);

        var children = g.selectAll(".child")
            .data(function (d) {
                return d._children || [d];
            })
            .enter().append("g") //SHOW CHILDREN FROM TREEMAP VIEW
            .style("opacity", 0.7); // DEFINES THE OPACITY OF THE INTERNAL NODES

        children.append("rect")
            .attr("class", "child")
            .call(rect)
            .append("title")
            .text(function (d) {
                return d.data.name + " (" + formatNumber(d.data.value) + ")";
            });


        children.append("text")
            .attr("class", "ctext").style("font-size", "14px")
            .text(function (d) {
                return d.data.name;
            })
            .call(text2);

        g.append("rect")
            .attr("class", "parent")
            .call(rect);

        //MOUSEOVER: SHOW CHILDREN OF THE NODES
        g.selectAll("rect").classed("parent", true).on("mouseover", function (d) {
            d3.select(this).style("opacity", 0.3); //.
            tooltip.html(d.data.name + "<br/>" + formatNumber(d.data.value));
            tooltip.transition();
            return tooltip.style("visibility", "visible").style("opacity", 1);
            //children.select("g").style("opacity", 1);
        });
        //MOUSEOUT: HIDE CHILDREN OF THE NODES
        g.selectAll("rect").classed("parent", false).on("mouseout", function () {
            d3.select(this).style("opacity", 1);
            return tooltip.style("visibility", "hidden");
        });

        g.selectAll("rect").classed("parent", false).on("mousemove", function () {
            d3.select(this).style("opacity", 0.3);
            tooltip.style("opacity", 1);
            return tooltip.style("top", (d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px");
        });

        var t = g.append("text")
            .attr("class", "ptext").style("font-weight", "bold")
            .attr("dy", ".75em");

        t.append("tspan")
            .attr("font-weight", "bold")
            .text(function (d) {
                return d.data.name;
            });

        t.append("tspan")
            .attr("dy", "1.0em")
            .text(function (d) {
                return formatNumber(d.data.value);
            });

        t.call(text);

        g.selectAll("rect")
            .style("fill", function (d) {
                return color(d.data.value);
            });

        function transition(d) {
            // Handle Parcoords data
            Shiny.onInputChange("scope", d.data.escopo);
            Shiny.onInputChange("name", d.data.name);
            Shiny.addCustomMessageHandler("treemap2_values_change", function (message) {
                if (d.data.children[0]) {
                    nextScope = d.data.children[0].escopo;

                    var toColorDup = message[nextScope];
                    toColor = toColorDup.filter(function (elem, index, self) {
                        return index === self.indexOf(elem);
                    });


                    console.log(toColor);
                    var i0;
                    colors_subtitle = [];
                    for (i0 = 0; i0 < toColor.length; i0++) {
                        colors_subtitle.push({
                            name: toColor[i0],
                            color: colorMake(i0)
                        });
                    }
                    
                    d3.select("#parallel_coordinates_subtitle").selectAll('div').remove();
                    s1 = d3.select("#parallel_coordinates_subtitle").selectAll('div').data(colors_subtitle).enter().append("div").append("text");
                    
                    s1Attr = s1.text(function (d) {
                            return d.name;
                        })
                        .style("color", function (d) {
                            return d.color;
                        })
                        .style("font-weight", "bold");

                } else {
                    nextScope = "municipio"
                }

                traits = ["name", 'value', "Hora", "Dia", "Idade", "Sexo", "Causador"];
                message = transposeData(message);
                d3.select("#parallelcoordinates_switch_cities").selectAll("*").remove();
                reloadCheckBoxesCities(message)
                d3.select("#parallelcoordinates_area_cities svg").remove();
                reloadParallelCordsCities(message);


            });
            d3.select("#parallelcoordinates_switch").selectAll("*").remove();
            reloadCheckBoxes(d.data.children);
            d3.select("#parallelcoordinates_area svg").remove();
            reloadParallelCords(d.data.children);
            if (transitioning || !d) return;
            transitioning = true;
            var g2 = display(d),
                t1 = g1.transition().duration(750),
                t2 = g2.transition().duration(750);
            // Update the domain only after entering new elements.
            //x.domain([d.x0, d.x0 + d.x1]);
            //y.domain([d.y0, d.y0 + d.y1]);
            x.domain([d.x0, d.x0 + (d.x1 - d.x0)]);
            y.domain([d.y0, d.y0 + (d.y1 - d.y0)]);

            // Enable anti-aliasing during the transition.
            treemap.style("shape-rendering", null);

            // Draw child nodes on top of parent nodes.
            //treemap.selectAll(".depth").sort(function(a, b) { 
            //console.log('.depth sort a ' + a.depth + ' b ' + b.depth);
            //return a.depth - b.depth; });

            // Fade-in entering text.
            g2.selectAll("text").style("fill-opacity", 0);

            // Transition to the new view.
            t1.selectAll(".ptext").call(text).style("fill-opacity", 0).style("font-weight", "bold"); //.style("font-size", "12px");
            t2.selectAll(".ptext").call(text).style("fill-opacity", 1).style("font-weight", "bold"); //.style("font-size", "12px");
            t1.selectAll(".ctext").call(text2).style("fill-opacity", 0);
            t2.selectAll(".ctext").call(text2).style("fill-opacity", 1);
            t1.selectAll("rect").call(rect); //.style("fill", function(d) { return color(d.data.value); });
            t2.selectAll("rect").call(rect); //.style("fill", function(d) { return color(d.data.value); });

            // Remove the old node when the transition is finished.
            t1.remove().on("end", function () {
                treemap.style("shape-rendering", "crispEdges");
                transitioning = false;
            });
        }
        return g;
    }

    function make_title(d) {
        //console.log("making_title", d);
        return d ? d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
    }

    function text(text) {
        text.selectAll("tspan")
            .attr("x", function (d) {
                return x(d.x0) + 5;
            });
        text.attr("x", function (d) {
                return x(d.x0) + 5;
            })
            .attr("y", function (d) {
                return y(d.y0) + 3;
            })
            .style("opacity", function (d) {
                var w = x(d.x1) - x(d.x0);
                //console.log("text opacity setting textlength " + this.getComputedTextLength() + " d size " + w);
                return this.getComputedTextLength() <= w ? 1 : 0;
            })
            .style("font-size", "10px");
    }

    function text2(text) {
        text
            .attr("x", function (d) {
                // console.log(d.data.name);
                // console.log( this.getComputedTextLength() );    
                return x(d.x1) - this.getComputedTextLength() - 2;
            })
            .attr("y", function (d) {
                return y(d.y1) - 2;
            })
            .style("opacity", function (d) {
                var w = x(d.x1) - x(d.x0);
                //console.log("text2 opacity setting textlength " + this.getComputedTextLength() + " d size " + w);
                return this.getComputedTextLength() <= w ? 1 : 0;
            })
            .style("font-size", "14px");
    }

    function rect(rect) {
        rect.attr("x", function (d) {
                return x(d.x0);
            })
            .attr("y", function (d) {
                return y(d.y0);
            })
            .attr("width", function (d) {
                var w = x(d.x1) - x(d.x0) - 1;
                //console.log('id ' + d.id +' rect width ' + w);
                return w;
            })
            .attr("height", function (d) {
                var h = y(d.y1) - y(d.y0);
                //console.log('id ' + d.id +' rect height ' + h);
                return h;
            })
            .style("stroke", "darkblue")
            .style("stroke-width", 1);
    }

    function name(d) {
        return d.parent ? name(d.parent) + " -> " + d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
    }




});